package com.lagou.app;

import com.lagou.entity.Account;
import com.lagou.utils.DateUtils;
import com.lagou.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.w3c.dom.xpath.XPathResult;

import java.io.ObjectOutputStream;
import java.sql.SQLException;

/**
 * 测试类
 */

public class AccountTest {

    public static void main(String[] args) {

        //1.获取QueryRunner
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        //2.编写sql，求出两个账户此时的余额
        try {
            Account tom = queryBalance(qr,"1122334455");
            Account lucy = queryBalance(qr,"55443332211");
            //3.如果tom的余额大于5000，则向lucy转账5000元，否则显示余额不足，并结束进程
            if(tom.getBalance()>=5000){
                //4.tom向lucy转账5000元
                decrease(qr,tom);
                //4.1 记录tom的转账过程
                traAcount(qr,tom);
                //5.lucy接收tom的5000元
                increase(qr,lucy);
                //5.1 记录lucy的转账过程
                traAcount(qr,lucy);
            }else{
                System.out.println("余额不足");

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //查询当前账户信息
    public static Account queryBalance(QueryRunner qr, String card) throws SQLException {
        String sql = "select * from account where card = ?";
        return qr.query(sql,new BeanHandler<Account>(Account.class),card);
    }

    //减少账户当前余额
    public static void decrease(QueryRunner qr, Account account) throws SQLException {

        //2.编写sql
        String sql = "update account set balance = ? where card = ?";
        Object[] param = {account.getBalance() - 5000, account.getCard()};
        qr.update(sql,param);
    }

    //增加账户当前余额
    public static void increase(QueryRunner qr, Account account) throws SQLException {
        //2.编写sql
        String sql = "update account set balance = ? where card = ?";
        Object[] param = {account.getBalance() + 5000, account.getCard()};
        qr.update(sql,param);
    }

    //转账信息
    public static void traAcount(QueryRunner qr, Account account) throws SQLException {
        String sql = "insert into transaction(cardid,tratype,tramoney,tradate) values (?,?,?,?)";
        Object[] param = null;
        if (account.getCard().equals("1122334455")){
            param = new Object[]{account.getCard(), "转出", 5000, DateUtils.getDateFormart()};
        }else if (account.getCard().equals("55443332211")){
            param = new Object[]{account.getCard(), "转入", 5000, DateUtils.getDateFormart()};
        }
        qr.update(sql, param);
    }


}
